/**
 * Created by lvlq on 16/4/30.
 */
var express = require("express");
var router = express.Router();
var Q = require("q");
var sequelize = require("sequelize");
var csv = require("csv");

router.get("/export", function (req, res) {
    res.render("mzrq/index.html");
});


router.get("/exportFile", function (req, res) {
    var pid = req.query.pid;
    var num = req.query.num;
    var iconvs = req.query.iconv;//'gb2312'
    getOpenidsByPid(pid, num).then(function (data) {
        for (var i = 0; i < data.length; i++) {
            var val = data[i].nick;
            var s = new Buffer(val, 'base64').toString();
            data[i].nick = s;
        }

        var title = {
            openid: "微信openid",
            nick: "微信昵称",
            phone: "手机号",
            time: "时间"
        };
        data.unshift(title);
        var titlename = 'error';
        if (pid == 1) {
            titlename = "玛力随行杯获奖数据";
        } else if (pid == 2) {
            titlename = "玛力充气泵获奖数据";
        } else if (pid == 3) {
            titlename = "汤尤杯门票获奖数据";
        }
        var name = encodeURI(titlename);
        res.setHeader('Content-disposition', 'attachment; filename=' + name + '.csv');
        res.writeHead(200, {'Content-Type': 'text/csv'});
        csv.stringify(data, function (err, d) {
            var iconv = require('iconv-lite');
            var str = iconv.encode(d, iconvs);
            res.write(str);
            res.end();
        });
        res.json({
            data: data
        });
    }).catch(function (err) {
        res.json({
            err: err.message
        })
    });
});


/**
 * 通过pid获取openid列表
 * @param pid
 * @returns {promise.promise|*|jQuery.promise|promise|d.promise}
 */
var getOpenidsByPid = function (pid, num) {
    var defer = Q.defer();
    var Log = M("index.log");
    var Wx = M("index.wx");
    Log.findAll({
        where: {
            pid: pid
        },
        group: "q_openid",
        attributes: [['q_openid', 'openid'], [sequelize.fn('COUNT', '1'), 'count']],
        having: {
            count: num
        }
    }).then(function (data) {
        var openids = [];
        for (var i = 0; i < data.length; i++) {
            openids.push(data[i].openid);
        }

        return Wx.findAll({
            where: {
                openid: openids
            },
            attributes: ['openid', 'nick', 'phone', [sequelize.fn("date_format", sequelize.col('updatedAt'), '%Y-%m-%d %H:%i:%s'), "time"]],
            order: [['updatedAt', 'asc']]
        });
    }).then(function (data) {
        defer.resolve(data);
    }).catch(function (err) {
        defer.reject(err);
    });
    return defer.promise;
};

module.exports = router;